package com.ebupt.migu.restapi;

import java.io.File;
import java.util.Arrays;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.ebupt.migu.common.pojo.TaskSend;
import com.ebupt.migu.common.pojo.TaskSendRep;
import com.ebupt.migu.common.response.Response;
import com.ebupt.migu.common.response.ResponseBean;
import com.ebupt.migu.common.util.PropertiesUtil;
import com.jcraft.jsch.ChannelSftp;

import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.crypto.SmUtil;
import cn.hutool.extra.ssh.JschUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author tz
 */
@Component
@Slf4j
public class DownloadByFtp {

    private static PropertiesUtil prop = new PropertiesUtil();
    private static String SFTP_IP = prop.getValue("sftpHost");
    private static int PORT = Integer.parseInt(prop.getValue("sftpPost"));
    private static String SFTP_USER = prop.getValue("sftpUser");
    private static String SFTP_PWD = prop.getValue("sftpPwd");

    /**
     * 标签平台客群解密后文件存放路径
     */
    private static File getFileData(String filePath, String key) {
        String dirPath = filePath.substring(0, filePath.lastIndexOf("/") + 1);
        log.info("dir path:{}", dirPath);
        String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
        log.info("file name:{}", fileName);
        File localFile = new File(fileName);
        File resultFile = new File(fileName.split("\\.")[0] + "_result.txt");
        log.info("SFTP_IP:{}, PORT:{}, SFTP_USER:{}, SFTP_PWD:{}", SFTP_IP, PORT, SFTP_USER, SFTP_PWD);
        // 从对端sftp获取加密文件
        ChannelSftp sftp = JschUtil.openSftp(JschUtil.openSession(SFTP_IP, PORT, SFTP_USER, SFTP_PWD, 15000), 15000);
        try {
            sftp.cd(dirPath);
            log.info("切换path:{}", dirPath);
            sftp.get(fileName, localFile.getAbsolutePath());
            log.info("下载路径：{}", localFile.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sftp.disconnect();
        }
        // 文件解密
        log.info("文件解密-KEY:{},local file:{}, result file:{}", key, localFile, resultFile);
        return decryptToFile(key, localFile, resultFile) ? resultFile : null;
    }

    public static File getLabelUserGroup(Map<String, Object> strategy, String postUrl, int dataType) {
        // 构造请求参数，发送请求
        TaskSend taskSend = new TaskSend();
        taskSend.setActivityId(strategy.get("strategyId").toString())
            .setActivityName(strategy.get("strategyName").toString()).setPlanId(strategy.get("strategyId").toString())
            .setPlanName(strategy.get("strategyName").toString()).setCustomerId(strategy.get("groupId").toString())
            .setDataType(dataType).setAppreoverName("".equals(strategy.get("approverName").toString())
                ? strategy.get("creatorName").toString() : strategy.get("approverName").toString());
        RestHttpPost post = new RestHttpPost();
        Response<String> response = post.doRest(taskSend, postUrl);
        if ("0000".equals(response.getHead().getResponseCode())) {
            ResponseBean res = JSON.parseObject(response.getResponse(), ResponseBean.class);
            if (null != res.getData()) {
                TaskSendRep rep = JSON.toJavaObject((JSON)res.getData(), TaskSendRep.class);
                // 发送请求，获取解密文件
                return getFileData(rep.getFilePath(), rep.getSecretKey());
            }
        }
        return null;
    }

    /**
     * 获取G推需要的客群
     *
     * @param customerId
     * @param uuid 任务ID
     * @param postUrl
     * @param dataType
     * @param creator G推账号登录名
     * @return
     */
    public static File getLabelUserGroupForGPush(String customerId, String uuid, String postUrl, int dataType,
        String creator) {
        // 构造请求参数，发送请求
        TaskSend taskSend = new TaskSend();
        taskSend.setActivityId(uuid).setActivityName(uuid).setPlanId(uuid).setPlanName(uuid).setCustomerId(customerId)
            .setDataType(dataType).setAppreoverName(creator);
        RestHttpPost post = new RestHttpPost();
        Response<String> response = post.doRest(taskSend, postUrl);
        if ("0000".equals(response.getHead().getResponseCode())) {
            ResponseBean res = JSON.parseObject(response.getResponse(), ResponseBean.class);
            if (null != res.getData()) {
                TaskSendRep rep = JSON.toJavaObject((JSON)res.getData(), TaskSendRep.class);
                // 发送请求，获取解密文件
                return getFileData(rep.getFilePath(), rep.getSecretKey());
            }
        }
        return null;
    }

    /**
     * 文件解密 (文件)
     *
     * @param key
     * @param inFile
     * @return
     */
    private static boolean decryptToFile(String key, File inFile, File outFile) {
        if (inFile.exists()) {
            String decryptStr = SmUtil.sm4(key.getBytes()).decryptStr(new FileReader(inFile).readString());
            new FileWriter(outFile).writeLines(Arrays.asList(decryptStr.split(",")));
            inFile.delete();
            log.info("decrypt down!");
            return true;
        }
        return false;
    }

}
